import socket
import matplotlib.pyplot as plt
import numpy as np
from collections import deque
from pylab import mpl
import pymysql
import time
# 数据库配置
DB_CONFIG = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': 'hsp',
    'database': 'tcp_data_db',
    'port': 3306
}
# 服务端监听地址和端口
HOST = '127.0.0.1'
PORT = 8888

# 设置中文显示字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
# 设置正常显示符号
mpl.rcParams["axes.unicode_minus"] = False
np.set_printoptions(formatter={'float': '{: .1f}'.format})

# 初始化队列，最多存 20 个数据
data_queue = deque(maxlen=20)
# 创建 TCP 服务端套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))#绑定端口
server_socket.listen(5)
print("等待客户端连接...")
# 接受客户端连接
client_socket, addr = server_socket.accept()#阻塞等待
print(f"客户端已连接: {addr}")
client_info = f"{addr[0]}:{addr[1]}"


# 初始化 matplotlib 绘图
plt.ion()  # 开启交互模式
fig, ax = plt.subplots()#代表整个图形（Figure）用于设置图形级别的属性，代表坐标轴后续对曲线、柱状图、散点图等的绘制操作
# line, = ax.plot([], [], 'b-')  # 初始化曲线
ax.set_ylim(0, 100)  # 固定 Y 轴范围（根据需求调整）
ax.set_xlim(0, 20)  # X 轴对应队列长度
ax.set_title("实时数据曲线")
ax.set_xlabel("数据点")
ax.set_ylabel("数值")


# def save_to_db(timestamp, data, client_info):
#     """将数据保存到 MySQL 数据库"""
#     try:
#         print(f"尝试连接数据库: {DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}")
#         conn = pymysql.connect(**DB_CONFIG)
#         cursor = conn.cursor()
#
#         # 检查表格是否存在
#         cursor.execute("SHOW TABLES LIKE 'tcp_data'")
#         if cursor.fetchone() is None:
#             print("错误: 'tcp_data' 表不存在")
#             return
#
#         sql = "INSERT INTO tcp_data (timestamp, data_value, client_info) VALUES (%s, %s, %s)"
#         cursor.execute(sql, (timestamp, data, client_info))
#         conn.commit()
#         print("数据已成功存入数据库")
#     except pymysql.Error as e:
#         print(f"数据库连接错误: {e}")
#         # 打印错误代码和详细信息
#         print(f"错误代码: {e.args[0]}")
#         print(f"错误信息: {e.args[1]}")
#     finally:
#         if conn:
#             cursor.close()
#             conn.close()



try:
    while True:
        # 接收数据
        data = client_socket.recv(1024).decode().strip()
        if data:
            # 转换为浮点数
            num = int(data)
            data_queue.append(num)

            # 更新曲线数据
            x = np.arange(len(data_queue))
            # line.set_data(x, data_queue)
            ax.plot(x, data_queue, 'b-')  # 初始化曲线
            # 调整X轴标签
            if len(data_queue) < 20:
                ax.set_xlim(0, 20)
            else:
                ax.set_xlim(0, len(data_queue))
            # 重新绘制
            fig.canvas.draw()
            # 暂停刷新
            fig.canvas.flush_events()
            timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

            print(f"收到数据: {num}，当前队列: {list(data_queue)}")
except KeyboardInterrupt:
    print("服务端停止")
finally:
    client_socket.close()
    server_socket.close()
    plt.ioff()  # 关闭交互模式
    plt.show()  # 保持最后一帧